package com.LC.Controller;

import com.LC.Constant.MessageConstant;
import com.LC.Constant.RedisMessageConstant;
import com.LC.Entity.Order;
import com.LC.Entity.Result;
import com.LC.Service.OrderService;
import com.LC.Utils.SMSUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
public class OrderController {

    @Autowired
    JedisPool jedisPool;
    @Reference
    OrderService orderService;

    @PostMapping("/Order")
    public Result submitOrder(@RequestBody Map map) {
        //判断用户输入的验证码是否正确
        //1.从Redis中获取保存的验证码
        String ValidateCode = jedisPool.getResource().get(map.get("telephone") + RedisMessageConstant.SENDTYPE_ORDER);
        //2.将用户输入的验证码和Redis中的验证码比较
        String validateCode = map.get("validateCode").toString();
        Result orderResult = null;
        if (ValidateCode != null && validateCode != null && ValidateCode.equalsIgnoreCase(validateCode)) {
            //3.如果对比成功，调用service完成预约业务处理
            try {
                //设置预约类型为微信预约
                map.put("orderType", Order.ORDERTYPE_WEIXIN);
                orderResult = orderService.NewOrder(map);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,MessageConstant.ORDER_FAIL);
            }
            if (orderResult.isFlag()){
                //预约成功，向用户发送预约成功短信
                try {
                    SMSUtils.sendInformMessage(SMSUtils.ORDER_NOTICE,map.get("telephone").toString(),map.get("name").toString());
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
        } else {
            //4.如果验证码对比不成功，返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        return orderResult;
    }

    @GetMapping("/Order/{id}")
    public Result OrderById(@PathVariable int id){
        Map map = null;
        try {
            map = orderService.OrderInfoById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
        return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
    }
    
    
}
